package logic

import (
	"context"
	"errors"
	"user_svc/internal/svc"
	"user_svc/models"
	"user_svc/pkg"
	"user_svc/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type RealNameAuthLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRealNameAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RealNameAuthLogic {
	return &RealNameAuthLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RealNameAuthLogic) RealNameAuth(in *user.RealNameAuthRequest) (*user.RealNameAuthResponse, error) {
	// todo: add your logic here and delete this line
	var err error
	var r models.RealNameUser
	r.UserId = in.UserId

	if err = r.GetRealNameByUserId(); err != nil {
		logx.Error("通过UserId获取用户信息获取失败")
		return nil, errors.New("通过UserId获取用户信息获取失败")
	}

	if r.ID != 0 {
		logx.Error("用户已实名")
		return nil, errors.New("用户已实名")
	}

	if !pkg.RealNameAuth(in.IdCard, in.RealName) {
		logx.Error("实名失败：第三方实名认证接口")
		return nil, errors.New("实名失败：第三方实名认证接口")
	}

	r.IdCard = in.IdCard
	r.RealName = in.GetRealName()

	if err = r.CreateRealName(); err != nil {
		logx.Error("实名信息创建失败")
		return nil, errors.New("实名信息创建失败")
	}

	return &user.RealNameAuthResponse{
		UserId: r.UserId,
	}, nil
}
